package vy.org.app.page.printlabel.report.instance;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.vy.dal.dao.VyPrintLabelReportDAO;
import org.vy.dal.dao.VyPrintLabelReportDO;
import org.vy.dal.dao.VyPrintLabelReportInstanceDAO;
import org.vy.dal.dao.VyPrintLabelReportInstanceDO;

import vy.org.app.common.BaseAction;
import vy.org.app.common.ModuleEnum;

public class MntnPrintLabelReportInstanceAction extends BaseAction {

	@Override
	public ActionForward executeAction(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		MntnPrintLabelReportInstanceForm form = (MntnPrintLabelReportInstanceForm)actionForm;
		
		if(form == null){
			form = new MntnPrintLabelReportInstanceForm();
		}
		request.setAttribute("mntnPrintLabelReportInstanceForm", form);
		
		try {
			String ops = request.getParameter("ops");
			if(form.getReportId() == null || form.getReportId() == -1){
				ops = null;
			}
			if (ops == null || ops.equalsIgnoreCase("SHOW")) {
				List<VyPrintLabelReportDO> lst = VyPrintLabelReportDAO.findAll();
				((MntnPrintLabelReportInstanceForm)actionForm).setReports(lst);
			} else if (ops.equalsIgnoreCase("RUN")) {
				ReportManager.getInstance().createNewInstance(Integer.parseInt(request.getParameter("reportId")), request.getParameter("reportType"));
			} else if (ops.equalsIgnoreCase("CANCEL")) {
				ReportManager.getInstance().cancelRun(Integer.parseInt(request.getParameter("reportId")));
			} else if (ops.equalsIgnoreCase("DOWNLOAD")) {
				VyPrintLabelReportInstanceDO dto = VyPrintLabelReportInstanceDAO.findDataByReportInstanceId(Integer.parseInt(request.getParameter("reportInstanceId")));
				request.setAttribute("REPORT", dto.getReportData());
				return mapping.findForward("download");
			}
			if(((MntnPrintLabelReportInstanceForm)actionForm).getReportId() != null 
					&& form.getReportId() != null && form.getReportId() != -1){
				List<VyPrintLabelReportInstanceDO> instances = VyPrintLabelReportInstanceDAO.findByReportId(((MntnPrintLabelReportInstanceForm)actionForm).getReportId());
				((MntnPrintLabelReportInstanceForm)actionForm).setInstances(instances);
			}
			if("RUN".equalsIgnoreCase(ops))
				return mapping.findForward("run");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("failure");
		}
		return mapping.findForward("success");
	}

	@Override
	protected ModuleEnum getModuleId() {
		return ModuleEnum.RUN_PRINT_LABEL_REPORT;
	}

}
